package pub.elephants.socket.netty.client;

import org.apache.commons.pool2.impl.GenericObjectPool;
import pub.elephants.serializable.ElephantsSerializable;

import java.util.concurrent.ConcurrentHashMap;

public class NettyClientPool {
    private GenericObjectPool<NettyClientPoolProxy>  pool;
    private static ConcurrentHashMap<String, NettyClientPool> clientPoolMap = new ConcurrentHashMap<String, NettyClientPool>();

    public NettyClientPool(String host, int port, ElephantsSerializable serializer) {
        pool = new GenericObjectPool<NettyClientPoolProxy>(new NettyClientPoolFactory(host, port, serializer));
        pool.setTestOnBorrow(true);
        pool.setMaxTotal(2);
    }

    /**
     * 获取默认pool
     * @return
     */
    public GenericObjectPool<NettyClientPoolProxy> getPool() {
        return pool;
    }

    /**
     * 使用注册中心
     * @param serverAddress
     * @param className
     * @param serializer
     * @return
     * @throws Exception
     */
    public static GenericObjectPool<NettyClientPoolProxy> getPool(String serverAddress, String className, ElephantsSerializable serializer)
            throws Exception {

        // valid serverAddress
        if (serverAddress==null || serverAddress.trim().length()==0) {
//            serverAddress = ZkServiceDiscovery.discover(className);
        }

        // get from pool
        NettyClientPool clientPool = clientPoolMap.get(serverAddress);
        if (clientPool != null) {
            return clientPool.getPool();
        }

        // init pool
        String[] array = serverAddress.split(":");
        String host = array[0];
        int port = Integer.parseInt(array[1]);

        clientPool = new NettyClientPool(host, port, serializer);
        clientPoolMap.put(serverAddress, clientPool);
        return clientPool.getPool();
    }
}
